package com.lishem.top100._08tree;

import com.lishem.common.TreeNode;

/**
 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/description/
 * <p>
 * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
 * <p>
 * 百度百科中最近公共祖先的定义为：“对于有根树 T 的两个节点 p、q，
 * <p>
 * 最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”
 */
public class _14LetCode236_二叉树的最近公共祖先 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p) {
            return root;
        }
        if (root == q) {
            return root;
        }
        TreeNode leftResult = lowestCommonAncestor(root.left, p, q);
        TreeNode rightResult = lowestCommonAncestor(root.right, p, q);
        if (leftResult != null && rightResult != null) {
            return root;
        } else if (leftResult != null) {
            return leftResult;
        } else if (rightResult != null) {
            return rightResult;
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        _14LetCode236_二叉树的最近公共祖先 sol = new _14LetCode236_二叉树的最近公共祖先();
        TreeNode root = new TreeNode(3);
        TreeNode p = new TreeNode(5);
        root.left = p;
        root.left.left = new TreeNode(6);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(7);
        root.left.right.right = new TreeNode(4);
        TreeNode q = new TreeNode(1);
        root.right = q;
        root.right.left = new TreeNode(0);
        root.right.right = new TreeNode(8);
        System.out.println(sol.lowestCommonAncestor(root, p, q).val);
    }
}
